{% set title = t("Download") + " " + film.title %}

{% extends 'layouts/layout.html' %}


{% block body %}
<div class="container-fluid">
  {% if messages.success %}
  <div role="alert" class="alert alert-success">
    {% for success in messages.success %}
    <div>{{ success.msg }}</div>
    {% endfor %}
  </div>
  {% endif %}
  {% if messages.error %}
  <div role="alert" class="alert alert-danger">
    {% for error in messages.error %}
    <div>{{ error.msg }}</div>
    {% endfor %}
  </div>
  {% endif %}
  {% if messages.info %}
  <div role="alert" class="alert alert-info">
    {% for info in messages.info %}
    <div>{{ info.msg }}</div>
    {% endfor %}
  </div>
  {% endif %}

</div>

<div class="row text-center">
  <img src="{{film.thumb480}}?resize=480,270&crop=entropy" width="300px" alt="{{film.title}}">
  <h2>{{ t("Download") }}</h2>
  <h3>{{ film.title }}</h3>
  <br>

  <button class="btn btn-default" onclick="startDownload()" id="start">{{t('Iniciar Download')}}</button>
  <br>
  <div class="log"></div>
  <div id="progress"></div>
</div>


<!-- Include the latest version of WebTorrent -->
<script src="https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script>
<script type="text/javascript" src="https://gitcdn.xyz/repo/Stuk/jszip/master/dist/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>

<script>
var client = new WebTorrent()
var zip = new JSZip()

// Add somre basic files to the zip
var promise = $.get("{{film.thumb480}}");
zip.file("cover.jpg", promise);

client.on('error', function(err) {
  console.error('ERROR: ' + err.message)
})

console.log('Olar');

function startDownload() {

  document.getElementById('start').style.display = 'none'

  var torrentId = 'magnet:?xt=urn:btih:fe336864c31785d7d22f2097f04d11207bc612fa&dn=Parece+Comigo+Trailer.mp4&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=ws%3A%2F%2Fod.lk%2Fs%2FOTRfMjEwNjg0Njlf%2FParece%2520Comigo%2520Trailer.mp4&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https://vdn.libreflix.org/libreflix/Parece%20Comigo%20Trailer.mp4&xs=https://guilmour.github.io/ventana/torrents/Parece%20Comigo%20Trailer.torrent'
  // var torrentId = 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent'

//log('Adding ' + torrentId)
  client.add(torrentId, onTorrent)
}

function onTorrent(torrent) {
  log('Got torrent metadata!')
  // log(
  //   'Torrent info hash: ' + torrent.infoHash + ' ' +
  //   '<a href="' + torrent.magnetURI + '" target="_blank">[Magnet URI]</a> ' +
  //   '<a href="' + torrent.torrentFileBlobURL + '" target="_blank" download="' + torrent.name + '.torrent">[Download .torrent]</a>'
  // )

  // Print out progress every 5 seconds
  var interval = setInterval(function() {
    log('Progress: ' + (torrent.progress * 100).toFixed(1) + '%')
  }, 1000)

  //Render all files into to the page

  torrent.files.forEach(function(file) {

    //file.appendTo('.log')
    //log('(Blob URLs only work if the file is loaded from a server. "http//localhost" works. "file://" does not.)')

    file.getBlobURL(function(err, url) {
      if (err) return log(err.message)
      log('File done.')
      //log('<a href="' + url + '" download="[Libreflix.org] ' + file.name + '"> <button class="btn btn-default" id="start">{{t('Salvar filme')}}</button> </a>')
      log('<a> <button class="btn btn-default" id="start" onclick="saveZip(zip)">{{t('Salvar filme')}}</button> </a>')
      // Add the blob file to a zip file.
      file.getBlob(function callback (err, blob) {
        console.log(blob);
        console.log('Estou aqui adicionando o blob dentro do zip');
        zip.file(file.name, blob);
        console.log('Adicionei');
      })
    })
  })
  // Function to add new weeb seed if number of peers is less than 3
  torrent.on('download', function (bytes) {
    console.log('just downloaded: ' + bytes)
    console.log('total downloaded: ' + torrent.downloaded)
    console.log('download speed: ' + torrent.downloadSpeed)
    console.log('progress: ' + torrent.progress)
  })

  torrent.on('done', function() {
    log('Progress: 100%')
    clearInterval(interval)
    console.log('Inicio timeout');
    // setTimeout(saveZip, 2000, zip);
    console.log('fim timeout');
  })
}

function saveZip(zip){
  console.log('Agora bora comprimir saporra');
  zip.generateAsync({type: "blob"}).then(function(content){
    zipfilename = "[Libreflix.org] " + "{{ film.title }}" + ".zip"
    saveAs(content, zipfilename)
  })
}


function log(str) {
  var p = document.createElement('p')
  p.innerHTML = str
  //     document.querySelector('.log').appendChild(p)
  document.getElementById("progress").innerHTML = str;
}
</script>
{% endblock %}
